define(['jquery-all', 'underscore'], function($, _) {
	var editors = Array(),
	    activeEditor;

	//define fud tab widget
	$.widget("fud.fudtabs", $.ui.tabs, {
		removeTab : function($it) {
			var _divId = $it.find('a[href]:first').attr('href');
			$it.remove();
			$(_divId).remove();
		},

		removeAll : function() {
			$nav = this.element.find(".ui-tabs-nav").find('li').each(function() {
				var $it = $(this);
				var _divId = $it.find('a[href]:first').attr('href');
				if (_divId) {
					$it.remove();
					$(_divId).remove();
				}
			});
		}
	});

	/********************************************************************/
	/**                        CONSTANTS 			                   **/
	/********************************************************************/
	var VW_DOCTYP = 'vw_docTyp';
	var VW_OPENDLG = 'vw_openDlg';
	var VW_CHECKDLG = 'vw_checkDlg';
	var VW_MASK = 'vw_mask';
	var VW_MASKTYP = 'vw_maskTyp';
	var VW_MASKSUB = 'vw_masksub';
	var VW_FUNCINFO = 'vw_funcInfo';
	var VW_METADATA = 'vw_metadata';
	var VW_DLG = "vw_dlg";

	var EDITOR_HISTORY_COUNT = 80;

	var TAB_TYPEN = ['anhang', 'begleittext', 'beschreib', 'comment', 'inhalt', 'inventarisierung', 'inventarisierungUb', 'pers', 'schlagwort'];

	/*
	var FELD_TYPEN = {
	'1' : ['@', 'x', '2 zeiliges Eingabefeld; ohne Textauszeichnungen'],
	'2' : ['@', 'x', '4 zeiliges Eingabefeld; ohne Textauszeichnungen'],
	'3' : ['@', 'x', '6 zeiliges Eingabefeld; ohne Textauszeichnungen'],
	'4' : ['@', 'x', '8 zeiliges Eingabefeld; ohne Textauszeichnungen'],
	'5' : ['@', 'x', '10 zeiliges Eingabefeld; ohne Textauszeichnungen'],
	'6' : ['@', 'x', '12 zeiliges Eingabefeld; ohne Textauszeichnungen'],
	'7' : ['@', 'x', '14 zeiliges Eingabefeld; ohne Textauszeichnungen'],
	'8' : ['@', 'x', '32 zeiliges Eingabefeld; ohne Textauszeichnungen'],
	'9' : ['@', 's', 'Mehrzeiliges Textfeld mit Auszeichnungsfunktionalität; wird zur Analyse verwendet; darf nur EINmal pro Dokumenttyp existieren!'],
	'b' : ['@', 'd', 'Dummy'],
	'd' : ['@', 's', 'standardisiertes Datum Eingabefeld "JJJJ-MM-TT"'],
	'e' : ['@', 'x', 'Auswahl aus einer Index-Tabelle; wie (a), jedoch aus einer "Extended"-Indextabelle.'],
	'f' : ['@', 's', 'Einzeiliges nur Lesen Feld (aus z)'],
	'g' : ['@', 'x', '!!! Auswahl aus einer Index-Tabelle; wie (e), jedoch nur lesend. kommt nur als Labelfeld vor'],
	'h' : ['@', 'x', 'Checkbutton'],
	'i' : ['@', 'x', 'Mehrzeiliges Textfeld mit Auszeichnungsfunktionalität; verwendet eigenen hebräischen Font'],
	'k' : ['@', 's', 'versch. Dokumente -> Binär Datei auswählen, hochladen, download bis zu 10 Felder möglich; Attribut tableField muss sourcename[0..9] sein'],
	'l' : ['@', 'x', 'Auswahl aus einer Index-Tabelle die sich auf die Dokumentgruppe bezieht; wie (c), jedoch aus einer "Extended"-Indextabelle.'],
	'm' : ['@', 's', 'visulles Medium -> Bild auswählen, hochladen, anzeigen bis zu 10 Felder möglich; Attribut tableField muss sourcename[0..9] sein'],
	'o' : ['@', 'x', 'Mehrzeiliges Textfeld mit Auszeichnungsfunktionalität'],
	'p' : ['@', '', 'Auswahl Indextabelle mit Scrollbar???'],
	'q' : ['@', 'x', '1:1 Beziehung (interne Verlinkung) ...'],
	'r' : ['@', 'x', 'nur Text (Angaben die aus einem anderen Dokument stammen z.B. bei Dokumenten zu einem Manteldokument)'],
	's' : ['@', 'd', 'Wiederholungsfeld (headdatasort MUSS -1 sein!)'],
	'u' : ['@', 'd', 'Aufruf eines Dokuments/Datei (z.B. Anleitung oder Hilfe) ueber einen Button'],
	'v' : ['@', 's', 'ZeitinterVall Eingabefeld"JJJJ-JJJJ","&gt;JJJJ"bzw."&lt;JJJJ"'],
	'w' : ['@', 'x', 'Verweis auf Webseite'],
	'y' : ['@', 'y', 'Mehrfachauswahl aus einer Index-Tabelle wie (x), jedoch aus einer "Extended"-Indextabelle (tableTyp y).'],
	'z' : ['@', 'x', 'Einzeiliges Eingabefeld'],
	'chmm' : ['@', 'x', '?'],
	'aa' : ['@', 'x', 'Automatische Zählung der Anzahl von Dateneinträge für ein wiederholbares Feld beim Speichern (Beispiel: Projektionskunst)'],
	'ab' : ['@', '', 'Rückverweis von internen Verlinkungen: Relation 1:n (Beispiel: Projektionskunst) In Entwicklung'],
	'ac' : ['@', '', 'Rückverweis von internen Verlinkungen: Relation 1:1 (Beispiel: Projektionskunst) In Entwicklung'],
	'zz' : ['@', 'x', 'Aufruf einer Funktion für ein Feld beim Speichern (Beispiel: Projektionskunst)']
	};*/

	//FELD_TYPEN = { [my_fieldTyp:{ fieldTyp,tableTyp,title}]}
	var FELD_TYPEN = {
		'1' : {
			fieldTyp : '1',
			tableTyp : 'x',
			title : '2 zeiliges Eingabefeld; ohne Textauszeichnungen'
		},
		'2' : {
			fieldTyp : '2',
			tableTyp : 'x',
			title : '4 zeiliges Eingabefeld; ohne Textauszeichnungen'
		},
		'3' : {
			fieldTyp : '3',
			tableTyp : 'x',
			title : '6 zeiliges Eingabefeld; ohne Textauszeichnungen'
		},
		'4' : {
			fieldTyp : '4',
			tableTyp : 'x',
			title : '8 zeiliges Eingabefeld; ohne Textauszeichnungen'
		},
		'5' : {
			fieldTyp : '5',
			tableTyp : 'x',
			title : '10 zeiliges Eingabefeld; ohne Textauszeichnungen'
		},
		'6' : {
			fieldTyp : '6',
			tableTyp : 'x',
			title : '12 zeiliges Eingabefeld; ohne Textauszeichnungen'
		},
		'7' : {
			fieldTyp : '7',
			tableTyp : 'x',
			title : '14 zeiliges Eingabefeld; ohne Textauszeichnungen'
		},
		'8' : {
			fieldTyp : '8',
			tableTyp : 'x',
			title : '32 zeiliges Eingabefeld; ohne Textauszeichnungen'
		},
		'9' : {
			fieldTyp : '9',
			tableTyp : 's',
			title : 'Mehrzeiliges Textfeld mit Auszeichnungsfunktionalität; wird zur Analyse verwendet; darf nur EINmal pro Dokumenttyp existieren!'
		},
		'b' : {
			fieldTyp : 'b',
			tableTyp : 'd',
			title : 'Dummy'
		},
		'd' : {
			fieldTyp : 'd',
			tableTyp : 's',
			title : 'standardisiertes Datum Eingabefeld "JJJJ-MM-TT"'
		},
		'e' : {
			fieldTyp : 'e',
			tableTyp : 'x',
			title : 'Auswahl aus einer Index-Tabelle; wie (a), jedoch aus einer "Extended"-Indextabelle.'
		},
		'f' : {
			fieldTyp : 'f',
			tableTyp : 's',
			title : 'Einzeiliges nur Lesen Feld (aus z)'
		},
		'f-timelastchg' : {
			fieldTyp : 'f',
			tableTyp : 's',
			title : 'timelastchg'
		},
		'f-timecreate' : {
			fieldTyp : 'f',
			tableTyp : 's',
			title : 'timecreate'
		},
		'g' : {
			fieldTyp : 'g',
			tableTyp : 'x',
			title : '!!! Auswahl aus einer Index-Tabelle; wie (e), jedoch nur lesend. kommt nur als Labelfeld vor'
		},
		'h' : {
			fieldTyp : 'h',
			tableTyp : 'x',
			title : 'Checkbutton'
		},
		'i' : {
			fieldTyp : 'i',
			tableTyp : 'x',
			title : 'Mehrzeiliges Textfeld mit Auszeichnungsfunktionalität; verwendet eigenen hebräischen Font'
		},
		'k' : {
			fieldTyp : 'k',
			tableTyp : 's',
			title : 'versch. Dokumente -> Binär Datei auswählen, hochladen, download bis zu 10 Felder möglich; Attribut tableField muss sourcename[0..9] sein'
		},
		'l' : {
			fieldTyp : 'l',
			tableTyp : 'x',
			title : 'Auswahl aus einer Index-Tabelle die sich auf die Dokumentgruppe bezieht; wie (c), jedoch aus einer "Extended"-Indextabelle.'
		},
		'm' : {
			fieldTyp : 'm',
			tableTyp : 's',
			title : 'visulles Medium -> Bild auswählen, hochladen, anzeigen bis zu 10 Felder möglich; Attribut tableField muss sourcename[0..9] sein'
		},
		'o' : {
			fieldTyp : 'o',
			tableTyp : 'x',
			title : 'Mehrzeiliges Textfeld mit Auszeichnungsfunktionalität'
		},
		'p' : {
			fieldTyp : 'p',
			tableTyp : '',
			title : 'Auswahl Indextabelle mit Scrollbar???'
		},
		'q' : {
			fieldTyp : 'q',
			tableTyp : 'x',
			title : '1:1 Beziehung (interne Verlinkung) ...'
		},
		'r' : {
			fieldTyp : 'r',
			tableTyp : 'x',
			title : 'nur Text (Angaben die aus einem anderen Dokument stammen z.B. bei Dokumenten zu einem Manteldokument)'
		},
		's' : {
			fieldTyp : 's',
			tableTyp : 'd',
			title : 'Wiederholungsfeld (headdatasort MUSS -1 sein!)'
		},
		'u' : {
			fieldTyp : 'u',
			tableTyp : 'd',
			title : 'Aufruf eines Dokuments/Datei (z.B. Anleitung oder Hilfe) ueber einen Button'
		},
		'v' : {
			fieldTyp : 'v',
			tableTyp : 's',
			title : 'ZeitinterVall Eingabefeld"JJJJ-JJJJ","&gt;JJJJ"bzw."&lt;JJJJ"'
		},
		'w' : {
			fieldTyp : 'w',
			tableTyp : 'x',
			title : 'Verweis auf Webseite'
		},
		'y' : {
			fieldTyp : 'y',
			tableTyp : 'y',
			title : 'Mehrfachauswahl aus einer Index-Tabelle wie (x), jedoch aus einer "Extended"-Indextabelle (tableTyp y).'
		},
		'z' : {
			fieldTyp : 'z',
			tableTyp : 'x',
			title : 'Einzeiliges Eingabefeld'
		},
		'chmm' : {
			fieldTyp : 'chmm',
			tableTyp : 'x',
			title : '?'
		},
		'aa' : {
			fieldTyp : 'aa',
			tableTyp : 'x',
			title : 'Automatische Zählung der Anzahl von Dateneinträge für ein wiederholbares Feld beim Speichern (Beispiel: Projektionskunst)'
		},
		'ab' : {
			fieldTyp : 'ab',
			tableTyp : '',
			title : 'Rückverweis von internen Verlinkungen: Relation 1:n (Beispiel: Projektionskunst) In Entwicklung'
		},
		'ac' : {
			fieldTyp : 'ac',
			tableTyp : '',
			title : 'Rückverweis von internen Verlinkungen: Relation 1:1 (Beispiel: Projektionskunst) In Entwicklung'
		},
		'zz' : {
			fieldTyp : 'zz',
			tableTyp : 'x',
			title : 'Aufruf einer Funktion für ein Feld beim Speichern (Beispiel: Projektionskunst)'
		},
		'ire1' : {
			fieldTyp : 'ire1',
			tableTyp : 'd',
			title : 'ire 1'
		},
		'ire2' : {
			fieldTyp : 'ire2',
			tableTyp : 'd',
			title : 'ire 2'
		},
		'ire3' : {
			fieldTyp : 'ire3',
			tableTyp : 'd',
			title : 'ire 3'
		},
		'ire4' : {
			fieldTyp : 'ire4',
			tableTyp : 'd',
			title : 'ire 4'
		}
	};

	var FUNCTION_OBJ = {
		"Funktionen" : [{
			"Name_intern" : "have_analyse",
			"Name_extern" : "Ist der Dokument analysiert.",
			"Discription" : "Gibt ein x zurück, falls der Dokument in FuD analysiert ist",
			"Feldtyp" : ""
		}, {
			"Name_intern" : "have_anhang",
			"Name_extern" : "Ist ein Bild oder Datei zu dieser Dokument angehängt",
			"Discription" : "Gibt ein x zurück, falls es Anhänge bzw. Images angehängt sind",
			"Feldtyp" : [{
				"Typ" : "k",
				"Description" : "Feldtyp für all möglichen Anhänge"
			}, {
				"Typ" : "m",
				"Description" : "Feldtyp für Images vom Format JPG, TIF und PNG"
			}]
		}, {
			"Name_intern" : "have_volltext",
			"Name_extern" : "Gibt es Text zu dieser Dokument",
			"Discription" : "Gibt ein x zurück, falls es Text gibt",
			"Feldtyp" : [{
				"Typ" : "9",
				"Description" : "Feldtyp für Textinhalt(formatierbar und analysiebar)"
			}]
		}, {
			"Name_intern" : "have_pic",
			"Name_extern" : "Ist ein Bild/Bilder zu dieser Dokument angehängt",
			"Discription" : "Gibt ein x zurück, falls es Images angehängt sind",
			"Feldtyp" : [{
				"Typ" : "m",
				"Description" : "Feldtyp für Images vom Format JPG, TIF und PNG"
			}]
		}, {
			"Name_intern" : "have_comment",
			"Name_extern" : "Ist ein Kommentar abgegeben",
			"Discription" : "Gibt ein x zurück, falls es ein Kommentar gibt",
			"Feldtyp" : [{
				"Typ" : "o",
				"Description" : "Feldtyp für Textinhalt(formatierbar). Im DB vw_mask muss die Spalte tableField=comment sein, sonst würde diese Funktion nicht funktionieren"
			}]
		}, {
			"Name_intern" : "have_index",
			"Name_extern" : "Ist der Dokument analysiert.",
			"Discription" : "Gibt ein x zurück, falls der Dokument in FuD Analysiert ist",
			"Feldtyp" : ""
		}, {
			"Name_intern" : "have_frei",
			"Name_extern" : "Ist der Dokument ein andere Person/Projekt frei gegeben.",
			"Discription" : "Gibt ein x zurück, falls der Dokument freigegebn worden ist",
			"Feldtyp" : ""
		}, {
			"Name_intern" : "get_timestamp",
			"Name_extern" : "Timestamp wann der Dokument zuletzt gespeichert worden ist",
			"Discription" : "Gibt ein Datum JJJJ-MM-TT zurück, wann der Dokument zuletzt gespeichert worden ist",
			"Feldtyp" : ""
		}, {
			"Name_intern" : "get_timestampopen",
			"Name_extern" : "Timestamp wann der Dokument zuletzt geöffnet worden ist",
			"Discription" : "Gibt ein Datum JJJJ-MM-TT zurück, wann der Dokument zuletzt geöffnet worden ist",
			"Feldtyp" : ""
		}]
	};

	/********************************************************************/
	/**                        Daten in SQL	  		                   **/
	/********************************************************************/
	var SqlData = {
		vw_metadata : {
			docTypeComment : 'Standarddokument'
		},

		vw_docTyp : {
			'ID' : '@',
			'docGroupID' : '0',
			'parentID' : '0',
			'data' : '@',
			'sort' : '@',
			'kurzel' : '@'
		},

		vw_openDlg : {
			'docTyp' : '@',
			'spalte1' : '',
			'spalte2' : '',
			'spalte3' : '',
			'spalte4' : '',
			'spalte5' : '',
			'spalte6' : '',
			'spalte7' : '',
			'spalte8' : '',
			'spalte9' : '',
			'spalte10' : '',
			'spalte11' : '',
			'spalte12' : '',
			'spalte13' : ''
		},

		vw_checkDlg : {
			'docTyp' : '@',
			'spalte1' : '',
			'spalte2' : '',
			'spalte3' : '',
			'spalte4' : '',
			'spalte5' : '',
			'spalte6' : '',
			'spalte7' : '',
			'spalte8' : '',
			'spalte9' : '',
			'spalte10' : '',
			'spalte11' : '',
			'spalte12' : '',
			'spalte13' : ''
		},

		vw_maskTyp : {
			'ID' : '0',
			'Name' : 'Name',
			'Bezeichnung' : '@',
			'Volltext_Suchflag' : '@'
		},

		vw_mask : {
			'ID' : '"0', //docTypID+3 stellelige Ziffer, automatisch erzeugt werden
			'docGroupID' : '@', //Eingabe von Benutzer oder aus SQL
			'docTypID' : '@', //Eingabe von Benutzer oder aus SQL
			'docSubTypID' : '0', // = "0"
			'maskTypID' : '@', //ID von DB tabelle "vw_maskTyp"
			'parentID' : '-1', //
			'elementText' : '', //
			'tableField' : '@', //
			'tableName' : '@', //
			'tableTyp' : '@', //
			'fieldTyp' : '1', //1,2,3,4......aa, ab, ... zz,
			'indexTable' : '', //?
			'vw_exportGruppeID' : '0', //?
			'headdatasort' : '-1', //= "-1"
			'sort' : '@', //automatisch erzeugt
			'obligatory' : '0', //0" / "1"
			'print_pos' : '', //
			'print_pre' : '', //
			'print_post' : '', //
			'publLemm_pos' : '', //
			'publLemm_pre' : '', //
			'publLemm_post' : '', //
		},

		vw_masksub : {
			'ID' : '"0',
			'docGroupID' : '@',
			'docTypID' : '@',
			'docSubTypID' : '0',
			'vw_maskID' : '@',
			'parentID' : '-1',
			'elementText' : '',
			'tableField' : '@',
			'tableName' : '@',
			'tableTyp' : '1',
			'fieldTyp' : '@',
			'indexTable' : '',
			'vw_exportGruppeID' : '0',
			'headdatasort' : '-1',
			'sort' : '@',
			'obligatory' : '0',
			'print_pos' : '',
			'print_pre' : '',
			'print_post' : '',
			'publLemm_pos' : '',
			'publLemm_pre' : '',
			'publLemm_post' : ''
		},

		vw_funcInfo : {
			'ID' : '',
			'docTypID' : '',
			'funcName' : '',
			'params' : ''
		},
	};

	/********************************************************************/
	/**                        SQL Parse                           **/
	/********************************************************************/
	var SQLParser = {
		/**
		 * @param {String} sql text
		 * @return {array}
		 */
		sql2Array : function(str) {
			var parseSql = SQLParser.getValueOfParenthesis,
			    lines = str.split("\n"),
			    outArr = Array(),
			    currRows,
			    currData,
			    out = '';
			for (var s,
			    i = 0,
			    l = lines.length; i < l; i++) {
				s = $.trim(lines[i]).replace(/\s+/g, ' ');
				s = s.replace(/[`]/g, '');
				if (s.match(/^#/)) {
					var cIndex = s.indexOf('#Dokumenttyp:');
					if (cIndex > -1) {
						outArr.push({
							'docTypeComment' : $.trim(s.substr(13))
						});
					}
					continue;
				}

				if (s == ' ') {
					continue;
				}

				if (s.match(/DELETE\sFROM/)) {
					var _data1 = SQLParser.getDocTypData(s);
					if (_data1) {
						var _idTyp = _data1[1];
						currRows = Array();
						currData = {
							'tbl' : _data1[0],
							_idTyp : _data1[2],
							'rows' : currRows
						};
						outArr.push(currData);
					}
				} else if (s.match(/INSERT\sINTO/)) {
					var _arr = s.split('VALUES');
					var _fieldData = parseSql(_arr[0]);
					if (_fieldData) {
						currData.field = _fieldData;
					}
					if (_arr[1]) {
						var _data3 = parseSql(_arr[1]);
						if (_data3) {
							currRows.push(_data3);
						}
					}
				} else {
					var _data2 = parseSql(s);
					if (_data2) {
						currRows.push(_data2);
					}
				}
			}
			return outArr;
		},

		/**
		 *
		 * @param{String} sql text
		 * @return {Array} [table,typeId, Id]
		 */
		getDocTypData : function(str) {
			var i = str.indexOf('FROM'),
			    j = str.indexOf('WHERE');
			if (i < 0 || j < 0) {
				return null;
			}
			var tbl = str.substring(i + 4, j);
			tbl = tbl.replace(/\s/g, '');

			var whereStr = $.trim(str.substring(j + 5));
			var arr,
			    ids;
			if (whereStr.match(/\sin\s/)) {
				arr = whereStr.split("in");
				ids = true;
			} else {
				arr = whereStr.split("=");
			}

			if (arr.length != 2) {
				return null;
			}

			var _idType = $.trim(arr[0]);
			var _id = arr[1];
			if (ids) {
				_id = _id.replace(/;/g, '');
				_id = $.trim(_id);

			} else {
				_id = _id.replace(/\D/g, '');
			}
			if (tbl && _idType && _id) {
				return [tbl, _idType, _id];
			}
			return null;
		},

		/**
		 *
		 * @param {String} str
		 * @return Werte innerhalb des Klammern
		 */
		getValueOfParenthesis : function(str) {
			var reg = /\(.*\)/ig;
			var arr = str.match(reg);
			var str = null;
			if (arr) {
				//remove ( )
				str = arr[0];
				str = str.replace(/[´]|^\s+|^\(|\)$|\s+$/g, '');
				str = str.replace(/\s+/g, ' ');
			}
			return str;
		},

		/**
		 *
		 * @param {Obj} vw_mask object
		 * @return {Array} [maskTypeId, newLiHtml]
		 */
		vw_mask_data_2Html : function(obj) {
			var ed = this;
			var title = obj['elementText'];
			var fieldType = my_fieldType = obj['fieldTyp'];
			var _tableField = obj['tableField'];
			if (_tableField == 'timelastchg') {
				my_fieldType = 'f-timelastchg';
			} else if (_tableField == 'timecreate') {
				my_fieldType = 'f-timecreate';
			}

			var content,
			    _style = '',
			    standardWidth = 600,
			    reqStr = '';

			if (obj['obligatory'] == "1") {
				reqStr = '*';
			}

			var _getTextarea = function(rowsCount) {
				return '<textarea rows="' + rowsCount + '" style="width:99%"></textarea>';
			};

			switch(fieldType) {
			case '1':
				content = _getTextarea(2);
				break;

			case '2':
				content = _getTextarea(4);
				break;

			case '3':
				content = _getTextarea(6);
				break;

			case '4':

				content = _getTextarea(8);
				break;

			case '5':
				content = _getTextarea(10);
				break;

			case '6':
				content = _getTextarea(12);
				break;

			case '7':
				content = _getTextarea(14);
				break;

			case '8':
				content = _getTextarea(32);
				break;

			case '9':
				content = '<img src="css/images/federtyp-9.jpg" />';
				break;

			case 'b':
				_style = 'background-color:#cccccc;';
				content = '&nbsp;';
				break;

			case 'd':
				content = '<input type="text" style="width:' + (standardWidth - 260) + 'px" /> Nur Eingaben in der Form \'JJJJ-MM-TT\'';
				break;

			case 'e':
				content = '<input type="button" value="ausw&auml;hlen" />';
				break;

			case 'f':
				content = '<input type="text" style="width:99%; background-color:#cccccc" />';
				break;

			case 'g':
				content = '&nbsp;';
				break;

			case 'h':
				_style = 'text-align:left';
				content = '<input type="checkbox"/>';
				break;

			case 'i':
				content = '<img src="css/images/federtyp-i.jpg" />';
				break;

			case 'k':
				content = '<input type="button" value="' + title + ' ausw&auml;hlen" />';
				break;

			case 'l':
				content = '<input type="button" value="ausw&auml;hlen" />';
				break;

			case 'm':
				content = '<input type="button" value="' + title + ' ausw&auml;hlen" />';
				break;

			case 'o':
				content = '<img src="css/images/federtyp-o.jpg" />';
				break;

			case 'p':
				content = 'Begriff: <input type="button" value="hinzuf&uuml;gen" /><input type="button" value="entfernen" />';
				break;

			case 'q':
				content = '<input type="button" value="' + title + ' ausw&auml;hlen" />';
				break;

			case 'r':
				content = '&nbsp;';
				break;

			case 's':
				_style = "text-align:center";
				content = '<input type="button" value="hinzuf&uuml;gen" />';
				break;

			case 'u':
				title = '';
				content = '<input type="button" value="Datum" />';
				break;

			case 'v':
				content = '<input type="text" style="width:' + (standardWidth - 350) + 'px" /> Nur Eingaben in den Formen \'JJJJ-JJJJ\',\'&gt;JJJJ\' bzw.\'&lt;JJJJ\'';
				break;

			case 'w':
				content = '<input type="text" style="width:99%" />';
				break;

			case 'y':
				content = 'Begriff: <input type="button" value="hinzuf&uuml;gen" /><input type="button" value="entfernen" />';
				break;

			case "z":
				content = '<input type="text" style="width:99%" />';
				break;

			case 'aa':
				content = '<input type="button" value="ausw&auml;hlen" />';
				break;

			case 'ab':
				_style = 'background-color:#cccccc;';
				content = '<input type="button" value="ausw&auml;hlen" />';
				break;

			case 'ac':
				content = '<input type="button" value="ausw&auml;hlen" />';
				break;

			case 'zz':
				content = '<input type="text" style="width:99%" />';
				break;

			}
			if (!content) {
				return '';
			}

			var attrStr = param(obj);
			var titleDiv = '<div class="fud-field-title">' + title + reqStr + '</div>';
			var contentDiv = '<div style="display:inline-block; text-align:right; width:' + standardWidth + 'px;' + _style + '">' + content + '</div>';
			return '<div class="fud-field-container" data-fudfield="' + attrStr + '" title="' + fieldType + ' - ' + FELD_TYPEN[my_fieldType]['title'] + '">' + titleDiv + contentDiv + '</div>';
		},

		/*
		 *
		 */
		rowToArray : function(rowStr) {
			var m1 = '@@_§§&';
			//für '
			var m2 = '@&_§@&_&@';
			//für ,

			rowStr = rowStr.replace(/\\'/g, m1);
			var m1Arr = rowStr.split("'");
			var newRowStr = '';
			for (var s,
			    i = 0,
			    l = m1Arr.length; i < l; i++) {
				s = m1Arr[i];
				if (i % 2 == 0) {
					s = s.replace(/,\s+/g, ',');
					newRowStr += s;
				} else {
					newRowStr += s.replace(/,/g, m2);
				}
			}
			var arr = newRowStr.split(',');
			for (var x = 0,
			    y = arr.length; x < y; x++) {
				arr[x] = arr[x].replace(/@@_§§&/g, "\'");
				arr[x] = arr[x].replace(/@&_§@&_&@/g, ",");
			}
			return arr;
		}
	};

	/*
	 *
	 */
	var deparam = function(pars) {
		pars = pars.replace(/\+/g, ' ');
		var arr = pars.split("&");
		var obj = {};
		for (var i = 0,
		    l = arr.length; i < l; i++) {
			var a = arr[i].split("=");
			var k = decodeURIComponent(a[0]);
			var v = decodeURIComponent(a[1]);
			obj[k] = v;
		}
		return obj;
	};

	/*
	 *
	 */
	var param = function(obj) {
		return $.param(obj);
	};

	/********************************************************************/
	/**                         Editor                                 **/
	/********************************************************************/
	var Editor = function(id) {
		this.initialize(id);
	};
	Editor.prototype = {
		/*
		 *
		 */
		actionCreateNewDocType : function($container) {
			var ed = this;

			var obj1 = ed.getVW_by_form(VW_METADATA, $container);
			var obj2 = ed.getVW_by_form(VW_DOCTYP, $container);
			if (obj1 && obj2) {
				ed.actionResetDocType();
				ed.setVW(VW_METADATA, _.toArray(obj1));
				ed.setVW(VW_DOCTYP, _.toArray(obj2));
				ed.setActionButtons(true);
				return true;
			}
			return false;
		},

		/*
		 *
		 */
		actionResetDocType : function() {
			var ed = this;
			var ui = ed.ui;
			if (ui) {
				var $tabs = ui.$tabs;
				$tabs.fudtabs('removeAll');
				$tabs.fudtabs("destroy");
				ui.$tabsNav = $tabs.fudtabs().find(".ui-tabs-nav");
			}
			ed.data = {
				freeID : {}
			};
		},

		/*
		 *
		 */
		actionSetSQL : function(str, add2H) {
			var ed = this;
			ed.actionResetDocType();

			var sqlArr = (SQLParser.sql2Array(str));
			var tabArr = Array();
			var tabDataArr = Array();
			var extendBlockMapping = {};
			try {
				for (var i = 0,
				    rows,
				    tbl,
				    item,
				    vwType,
				    sl = sqlArr.length; i < sl; i++) {
					item = sqlArr[i];
					if (item['docTypeComment'] != undefined) {
						ed.setVW(VW_METADATA, _.toArray(item));
						continue;
					}
					rows = item['rows'];
					vwType = item['tbl'];
					if (rows) {
						var rowArr,
						    dataArr;
						for (var j = 0,
						    rowArr,
						    lr = rows.length; j < lr; j++) {
							var rowArr = SQLParser.rowToArray(rows[j]);
							if (rowArr) {
								var obj = ed.setVW(vwType, rowArr);
								switch(vwType) {
								case VW_MASKTYP:
									var newTabData = ed.addNewTab(null, null, null, obj, false, true);
									tabArr[obj['ID']] = newTabData[0];
									tabDataArr.push(newTabData);
									break;

								case VW_MASK:
									if (obj['tableName'] == '_EXTEND_BLOCK') {
										extendBlockMapping[obj['ID']] = obj['maskTypID'];
										ed.set_tab_eb(tabArr[obj['maskTypID']], true);
										continue;
									}
									var divHtml = SQLParser.vw_mask_data_2Html(obj);
									if (divHtml) {
										ed.insertFieldToTab(tabArr[obj['maskTypID']], divHtml);
									}
									break;

								case VW_MASKSUB:
									var tabID = extendBlockMapping[obj['vw_maskID']];
									var divHtml = SQLParser.vw_mask_data_2Html(obj);
									if (divHtml) {
										ed.insertFieldToTab(tabArr[tabID], divHtml);
									}
									break;

								case VW_OPENDLG:
									//default nehmen
									break;

								case VW_CHECKDLG :
									break;

								case VW_FUNCINFO:
									break;

								case VW_METADATA:
									break;

								}

							}

						}
					}
				}
				ed.ui.$tabs.fudtabs('refresh');
				//format panel
				for (var x = 0,
				    td,
				    xLen = tabDataArr.length; x < xLen; x++) {
					td = tabDataArr[x];
					td[0].find("a:first").trigger("click");
					ed.formatTabPanel(td[1]);
				}
				tabDataArr[0][0].find("a:first").trigger("click");
			} catch(e) {
				console.log(e);
				$('<div title="Fehler" class="fud-dialog-default" style="color:red"><p>SQL Inhalt ungültig!</p></div>').dialog({
					modal : true/* ,
					 close:function(){
					 ed.ui.$importTextarea.focus();
					 }*/
				});
				ed.actionUndo();
				return false;
			}

			ed.setActionButtons(true);
			if (add2H) {
				ed.add2History();
			}
			return true;
		},

		/*
		 *
		 */
		actionRedo : function() {
			var ed = this;
			var idx = ed.historyIndex,
			    len = ed.historyData.length;
			if (idx >= 0 && idx < len) {
				ed.historyIndex++;
				idx++;
				ed.actionSetSQL(ed.historyData[idx], false);
				if (idx == len - 1) {
					ed.enableButton(ed.ui.$redo, false);
				}
			}
			if (idx > 0) {
				ed.enableButton(ed.ui.$undo, true);
			}
		},

		/*
		 *
		 */
		actionTest : function() {
			var ed = this;
			ed.actionResetDocType();
			$.get('scripts/fud/docs/copyof53.sql', function(str) {
				ed.actionSetSQL(str, true);
				return;
			});
		},

		/*
		 *
		 */
		actionUndo : function() {
			var ed = this;
			var $st = ed.redoSortable;
			if ($st) {
				//	$st.sortable("cancel");
			}
			var hd = ed.historyData;

			if (ed.historyIndex > 0) {
				ed.historyIndex--;
				ed.actionSetSQL(hd[ed.historyIndex], false);
			}

			if (ed.historyIndex == 0) {
				ed.enableButton(ed.ui.$undo, false);
			}

			if (ed.historyIndex == undefined) {
				if (hd && hd.length == 1) {
					ed.actionSetSQL(hd[0], false);
				}
			} else {
				ed.enableButton(ed.ui.$redo, true);
			}

		},

		/*
		 *
		 */
		add2History : function() {
			var ed = this;
			var l = ed.historyData.length;
			var idx = ed.historyIndex;
			if (l > EDITOR_HISTORY_COUNT) {
				ed.historyData.shift();
			}
			if (idx > -1 && idx < (l - 1)) {
				ed.historyData.splice(idx + 1, l - 1);
			}
			ed.historyData.push(ed.getSQL());

			var hIdx = ed.historyIndex = ed.historyData.length - 1;
			if (hIdx == 0) {
				ed.enableButton(ed.ui.$undo, false);
			} else {
				ed.enableButton(ed.ui.$undo, true);
			}
			ed.enableButton(ed.ui.$redo, false);
		},

		/**
		 * @return {Array} [new tab, panel of new tab]
		 */
		addNewTab : function($tabToClone, $beforeTab, $afterTab, vw_maskTypObj, addBlank, notRefresh) {
			var ed = this;
			var newId = ed.getRandomID('fud');
			var $newTab,
			    $newTabPanel;
			var $tabs = ed.ui.$tabs;
			var blankField = addBlank ? ed.ui.blankFieldTemplate : '';

			if ($tabToClone) {
				//Suche nach entsprechendem DiV
				var _divId = $tabToClone.find('a[href]:first').attr('class', '').attr('href');
				var $srcDiv = ed.ui.$container.find(_divId);
				var $newDiv = $srcDiv.clone(true);
				//Div Inhalt nach neuem Div kopieren
				$newDiv = $('<div>' + $newDiv.html() + '</div>');
				//Container für <li> fieldItem
				$newTabPanel = $newDiv.find('ul:first');
				var liList = $newTabPanel.find('li').each(function(i, li) {
					ed.updateFieldItemValue($(li));
				});

				$newDiv.attr('id', newId);
				$newDiv.insertAfter($srcDiv);
				//tab innerhalb toolbar
				$newTab = $tabToClone.clone(true);
				var $_a = $newTab.find('a[href]:first');
				$_a.attr('id', '');
				$_a.attr('href', '#' + newId);
				$_a.attr('data-fud_tab_id', ed.get_vw_freeID(VW_MASKTYP));
			} else {
				$newTab = $('<li><a href="#' + newId + '" data-fud_tab_id="' + vw_maskTypObj['ID'] + '" data-fud_tab_name="' + vw_maskTypObj['Name'] + '">' + vw_maskTypObj['Bezeichnung'] + '</a><span title="Wiederholungsfeld" class="fud-tab-eb"></span></li>');
				$newTabPanel = $('<ul class="fud-tab-panel ui-sortable">' + blankField + '</ul>');
				$div = $('<div id="' + newId + '"></div>');
				$div.append($newTabPanel);
				$tabs.append($div);
			}

			//make tabPanel sortable
			$newTabPanel.sortable({
				axis : 'y',
				cursor : 'move',
				update : function() {
					ed.redoSortable = $(this);
					ed.add2History();
				}
			});

			if ($beforeTab) {
				$newTab.insertBefore($beforeTab);
			} else if ($afterTab) {
				$newTab.insertAfter($afterTab);
			} else {
				$newTab.insertBefore(ed.ui.$buttonCreateTab.parent());
			}
			if (!notRefresh) {
				$tabs.fudtabs('refresh');
			}
			$newTab.find("a:first").trigger("click");
			return [$newTab, $newTabPanel];
		},

		/*
		 *
		 */
		arr2Sql : function(arr) {
			var out = '';
			for (var i = 0,
			    l = arr.length; i < l; i++) {
				out += arr[i];
				if (i == l - 1) {
					out += ';\n';
				} else {
					out += ',\n';
				}
			}
			return out;
		},

		/*
		 * bind button of toolbar and dialog
		 * @ isEditorButton {boolean} init is disable, after create/sql-import enable
		 */
		bindButtonAndDialog : function($toolbar, buttonName, dialogClass, isEditorButton) {
			var ed = this;
			var $dialog = ed.ui.$container.find('.' + dialogClass + ':first').dialog({
				autoOpen : false,
				dialogClass : 'fud-dialog-default',
				modal : true,
				height : "auto",
				width : "auto",
				open : function(event, ui) {
				}
			});
			if ($toolbar == null) {
				return $dialog;
			}

			var $button = $toolbar.find('*[name="' + buttonName + '"]:first');
			if (isEditorButton) {
				ed.ui.editorButtons.push($button);
			}
			$button.click(function(event) {
				if (isEditorButton && !ed.hasDoc) {
					return;
				}
				$dialog.dialog("open");
			});
			return $dialog;
		},

		/*
		 *
		 */
		checkAndAddBlankField : function($item) {
			var ed = this;
			var cList = $item.parent().find('li');
			if (cList.length < 2) {
				$(ed.ui.blankFieldTemplate).insertBefore($item);
			}
		},

		/*
		 *
		 */
		compareObj : function(obj1, obj2) {
			for (p in obj1) {
				if (obj1[p] != obj2[p]) {
					return false;
				}
			}
			return true;
		},

		constructor : Editor,

		/*
		 *
		 */
		enableButton : function($button, b) {
			if (!b) {
				$button.addClass('fud-button-disabled');
				$button.attr('disabled', true);
			} else {
				$button.removeClass('fud-button-disabled');
				$button.removeAttr('disabled');
			}
		},

		/*
		 *
		 */
		fill_dlg_edit : function($c, objStr) {
			var ed = this;
			var arr = ed.get_all_obj(),
			    selectHtml = '';
			for (var i = 0,
			    a,
			    lObj,
			    l = arr.length; i < l; i++) {
				a = arr[i];
				selectHtml += '<optgroup label="' + a['title'] + '">';
				lObj = a['liObj'];
				for (var x = 0,
				    obj,
				    y = lObj.length; x < y; x++) {
					obj = lObj[x];
					if (obj['tableField'] == 'dummy') {
						continue;
					}
					selectHtml += '<option value="' + obj['ID'] + '">' + obj['elementText'] + '</option>';
				}
				selectHtml += '</optgroup>';
			}
			selectHtml += '<optgroup style="color:blue" label="Funktion">';
			var fName;
			_.each(FUNCTION_OBJ.Funktionen, function(fun) {
				fName = fun.Name_intern;
				selectHtml += '<option value="' + fName + '">' + fName + '</option>';
			});

			var checkSelectVal = function(aSelect) {
				var selectList = $c.find('select');
				var $as = $(aSelect);
				var asVal = $as.val();
				var hasFunc = false;
				var hasId = false;
				for (var i = 0,
				    v,
				    sel,
				    l = selectList.length; i < l; i++) {
					sel = selectList[i];
					if (sel == aSelect) {
						continue;
					}

					v = $(sel).val();

					if (v && v != '') {
						if (!hasId && !isNaN(v)) {
							hasId = true;
						}
						if (!hasFunc && isNaN(v)) {
							hasFunc = true;
						}

						if ((hasId && isNaN(asVal)) || (hasFunc && !isNaN(asVal))) {
							alert('Diese Kombination ist nicht erlaubt.');
							$as.val($as.data('lastVal'));
							return;
						}

						if (asVal == v) {
							alert('Ausgewählte item schon vorhanden. Bitte andere versuchen.');
							$as.val($as.data('lastVal'));
							return;
						}
					}
				}
				$as.data('lastVal', asVal);
			};

			selectHtml += '</optgroup>';
			selectHtml = '<select><option value=""></option>' + selectHtml + '</select>';
			var objArr = objStr.split('#');
			var $ul = $('<ul></ul>');
			for (var m = 0,
			    $select,
			    $li,
			    $arrow,
			    $del,
			    $add,
			    len = objArr.length; m < len; m++) {
				$select = $(selectHtml);
				$select.change(function() {
					checkSelectVal(this);
				});
				$select.val(objArr[m]);
				$select.data('lastVal', objArr[m]);
				$li = $('<li><input type="checkbox" /></li>');
				$arrow = $('<img src="css/images/updown-arrow-16.png" style="cursor:move" />');
				$li.append($select);
				$li.append($arrow);
				$ul.append($li);
			}

			$ul.sortable({
				axis : 'y',
				cursor : 'move',
			});

			$c.html('');
			$c.append($ul);
		},

		/**
		 * For dialogSetup and dialogEdit
		 *
		 * @param $c container of inputs
		 */
		fillHtmlForm : function($c, vwType, obj) {
			var fList = $c.find('*[name*="' + vwType + '_"]');
			var l = fList.length;
			var $f,
			    k,
			    v;

			while (l--) {
				$f = $(fList[l]);
				k = $f.attr('name');
				var ak = k;
				k = k.replace(/[^_]*_[^_]*_/, '');
				if (k == 'obligatory') {
					if (obj[k] == 1) {
						$f.prop('checked', 'checked');
					} else {
						$f.prop('checked', false);
					}
					continue;
				}
				v = obj[k];
				if (v) {
					v = decodeURIComponent(v);
				} else {
					v = '';
				}
				if ($f.is(":input")) {
					$f.val(v);
				} else {
					$f.html(v);
				}
			}
		},

		/*
		 *
		 */
		formatTabPanel : function($tab) {
			var ed = this;
			var list = $tab.find('.fud-field-title');
			var l = list.length;
			if (l < 1) {
				$tab.append($(ed.ui.blankFieldTemplate));
				return;
			}

			var maxW = 0;
			var _px;
			for (var i = 0,
			    w; i < l; i++) {
				w = $(list[i]).css('width');
				if (!_px) {
					_px = w.replace(/[\d\s]/g, '');
				}
				w = parseInt(w);
				if (w > maxW) {
					maxW = w;
				}
			}

			for (var j = 0; j < l; j++) {
				$(list[j]).css('width', maxW + _px);
			}
		},

		/*
		 *
		 */
		get_all_obj : function() {
			var ed = this;
			var arr = Array();
			var $edc = ed.ui.$container;
			var $tabNav = ed.ui.$tabsNav;
			var aList = $tabNav.find('a[href*=#fud]');
			var $a,
			    _divID,
			    liList,
			    liObj;
			for (var i = 0,
			    l = aList.length; i < l; i++) {
				var obj = {};
				$a = $(aList[i]);
				obj['title'] = $a.html();
				obj['name'] = $a.attr('data-fud_tab_name');
				obj['isEB'] = ed.is_tab_eb($a.parent());
				_divID = $a.attr('href');
				$div = $edc.find(_divID);
				$ul = $div.find('ul:first');
				//obj['tabPanel'] = $ul; //nicht nötig
				liList = $ul.find('li');
				obj['liObj'] = Array();
				for (var x = 0,
				    y = liList.length; x < y; x++) {
					liObj = ed.get_obj_of_li($(liList[x]));
					obj['liObj'].push(liObj);
				}
				arr.push(obj);
			}
			return arr;
		},

		/*
		 *
		 */
		getDefaultVW : function(vwType) {
			var obj = _.clone(SqlData[vwType]);
			switch(vwType) {
			case VW_MASK:
				obj['docTypID'] = this.data[VW_DOCTYP]['ID'];
				obj['docGroupID'] = this.data[VW_DOCTYP]['docGroupID'];
				break;

			case VW_OPENDLG:
				obj['docTyp'] = this.data[VW_DOCTYP]['ID'];
				break;

			case VW_CHECKDLG:
				obj['docTyp'] = this.data[VW_DOCTYP]['ID'];
				break;
			}
			//TODO: andere type
			return obj;
		},

		/*
		 *
		 */
		get_obj_of_li : function($li) {
			if ($li.hasClass("fud-tab-blank-li")) {
				return null;
			}
			var data = $li.find('.fud-field-container:first').attr('data-fudfield');

			if (!data || (data == undefined)) {
				return null;
			} else
				return deparam(data);
		},

		/*
		 *
		 */
		getRandomID : function(c) {
			while (true) {
				var _id = c + new Date().getTime() + '' + Math.round(Math.random() * 1000);
				var $sel = $('#' + _id);
				if (!$sel || $sel.length < 1) {
					return _id;
				}
			}
		},

		/*
		 *
		 */
		getSQL : function() {
			var ed = this;
			var out = '';
			try {
				var vw_docTypID = ed.data[VW_DOCTYP]['ID'];
				var freeID = ed.get_vw_freeID(VW_MASK, false);

				//vw_maskTyp
				var vw_maskTyp_arr = Array(),
				    vw_maskTypIDs = Array(),
				    vw_maskTypName,
				    vw_maskTypID = parseInt(vw_docTypID + '01');
				//vw_mask
				var vw_mask_arr = Array();
				//vw_masksub
				var vw_masksub_arr = Array();

				var sortArr = {
					vw_mask : 10, //Abstand
					vw_masksub : 10 //Abstand
				};

				var extendBlockID;
				var tabsData = ed.get_ui_tabs_data();
				for (var i = 0,
				    _tab,
				    l = tabsData.length; i < l; i++) {
					extendBlockID = null;
					_tab = tabsData[i];

					/***find data of vw_maskTyp ***/
					vw_maskTypBez = _tab['title'];
					vw_maskTypIDs.push(vw_maskTypID);
					vw_maskTyp_arr.push("(" + vw_maskTypID + ",'" + _tab['name'] + "','" + vw_maskTypBez + "',1)");
					if (_tab['isEB']) {
						//add a row into vw_mask
						extendBlockID = freeID++;
						var ebObj = ed.getDefaultVW(VW_MASK);
						ebObj['ID'] = extendBlockID;
						ebObj['maskTypID'] = vw_maskTypID;
						ebObj['tableName'] = '_EXTEND_BLOCK';
						ebObj['fieldTyp'] = 's';
						ebObj['tableTyp'] = 'd';
						ebObj['sort'] = sortArr[VW_MASK];
						ebObj['tableField'] = ebObj['indexTable'] = '';
						sortArr[VW_MASK] = sortArr[VW_MASK] + 5;
						ed.obj2sql(vw_mask_arr, ebObj);
					}

					if (_tab['isEB']) {
						ed.push_sql_2_vw_mask_array(vw_masksub_arr, VW_MASKSUB, _tab['items'], extendBlockID, sortArr);
					} else {
						ed.push_sql_2_vw_mask_array(vw_mask_arr, VW_MASK, _tab['items'], vw_maskTypID, sortArr);
					}
					//nächste tab
					vw_maskTypID++;
				}

				var _getFieldSqlStr = function(vwType) {
					var fieldStr;
					for (var p in ed.getDefaultVW(vwType)) {
						if (p.match(/^tmp_/)) {
							continue;
						}

						if (!fieldStr) {
							fieldStr = '`' + p + '`';
						} else {
							fieldStr += ',`' + p + '`';
						}
					}
					return 'INSERT INTO `' + vwType + '` (' + fieldStr + ') VALUES\n';
				};

				var tmpObj = ed.getVW(VW_METADATA);
				if (tmpObj) {
					out += "#\n";
					out += "#Dokumenttyp: " + tmpObj['docTypeComment'];
				}

				tmpObj = ed.getVW(VW_DOCTYP);
				if (tmpObj) {
					//sql for vw_docTyp
					out += '\n\n\n';
					out += '# Tabelle `vw_docTyp`\n';
					out += '#\n';
					out += 'DELETE FROM `vw_docTyp` WHERE ID = ' + vw_docTypID + ';\n';
					out += _getFieldSqlStr(VW_DOCTYP);
					out += ed.obj2sql(null, tmpObj);
					out += ";";
				}

				//sql for vw_openDlg
				tmpObj = ed.getVW(VW_OPENDLG);
				if (tmpObj && ed.isObjEmpty(tmpObj, ['docTyp'])) {
					out += '\n\n\n';
					out += '# Tabelle `vw_openDlg`\n';
					out += '#\n';
					out += 'DELETE FROM `vw_openDlg` WHERE docTyp = ' + vw_docTypID + ';\n';
					out += _getFieldSqlStr(VW_OPENDLG);
					out += ed.obj2sql(null, tmpObj);
					out += ";";
				}

				//sql for vw_checkDlg
				tmpObj = ed.getVW(VW_CHECKDLG);
				if (tmpObj && ed.isObjEmpty(tmpObj, ['docTyp'])) {

					out += '\n\n\n';
					out += '# Tabelle `vw_checkDlg`\n';
					out += '#\n';
					out += 'DELETE FROM `vw_checkDlg` WHERE docTyp = ' + vw_docTypID + ';\n';
					out += _getFieldSqlStr(VW_CHECKDLG);
					out += ed.obj2sql(null, tmpObj);
					out += ";";
				}

				//sql for vw_maskTyp
				if (vw_maskTyp_arr.length > 0) {
					out += '\n\n\n';
					out += '# Tabelle `vw_maskTyp`\n';
					out += '#\n';
					out += 'DELETE FROM `vw_maskTyp` WHERE `ID` in (' + vw_maskTypIDs.join() + ');\n';
					out += _getFieldSqlStr(VW_MASKTYP);
					out += ed.arr2Sql(vw_maskTyp_arr);
				}

				//sql for vw_mask
				if (vw_mask_arr.length > 0) {
					out += '\n\n\n';
					out += '# Tabelle `vw_mask`\n';
					out += '#\n';
					out += 'DELETE FROM vw_mask WHERE docTypID = ' + vw_docTypID + ';\n';
					out += _getFieldSqlStr(VW_MASK);
					out += ed.arr2Sql(vw_mask_arr);
				}

				//sql for vw_masksub
				if (vw_masksub_arr.length > 0) {
					out += '\n\n\n';
					out += '# Tabelle `vw_masksub`\n';
					out += '#\n';
					out += 'DELETE FROM vw_masksub WHERE docTypID = ' + vw_docTypID + ';\n';
					out += _getFieldSqlStr(VW_MASKSUB);
					out += ed.arr2Sql(vw_masksub_arr);
				}

				//sql for vw_checkDlg
				tmpObj = ed.getVW(VW_FUNCINFO);
				if (tmpObj && tmpObj['ID'] != '' && tmpObj['ID'] != 0) {
					out += '\n\n\n';
					out += '# Tabelle `' + VW_FUNCINFO + '`\n';
					out += '#\n';
					out += 'DELETE FROM `' + VW_FUNCINFO + '` WHERE docTyp = ' + vw_docTypID + ';\n';
					out += _getFieldSqlStr(VW_FUNCINFO);
					out += ed.obj2sql(null, tmpObj);
					out += ";";
				}
			} catch(e) {
				out = 'Es wurde keinen SQL text erzeugt.';
			}

			return out;
		},

		/*
		 *
		 */
		getStringMax : function(str, max) {
			if (str.length > max) {
				str = str.substring(0, max);
			}
			return str;
		},

		/*
		 *
		 */
		get_ui_tabs_data : function() {
			var ed = this;
			var arr = Array();
			var $edc = ed.ui.$container;
			var $tabNav = ed.ui.$tabsNav;
			var aList = $tabNav.find('a[href*=#fud]');
			var $a,
			    _divID;
			for (var i = 0,
			    l = aList.length; i < l; i++) {
				var obj = {};
				$a = $(aList[i]);
				obj['title'] = $a.html();
				obj['name'] = $a.attr('data-fud_tab_name');
				obj['isEB'] = ed.is_tab_eb($a.parent());
				_divID = $a.attr('href');
				$div = $edc.find(_divID);
				$ul = $div.find('ul:first');
				//obj['tabPanel'] = $ul; //nicht nötig
				obj['items'] = $ul.find('li');
				arr.push(obj);
			}
			return arr;
		},

		/*
		 *
		 */
		get_vw_freeID : function(vwType, increment) {
			var ed = this;
			if (vwType == VW_MASKSUB) {
				vwType = VW_MASK;
			}

			var _id = ed.data.freeID[vwType];
			if (!_id) {
				//Automatische ID
				if (vwType == VW_MASK || vwType == VW_MASKTYP) {
					var docTypeID = ed.data[VW_DOCTYP]['ID'];
					var str = '001';
					if (vwType == VW_MASKTYP) {
						str = '01';
					}
					_id = docTypeID + str;
					ed.data.freeID[vwType] = _id;
				}
			}

			if (increment) {
				ed.use_vw_freeID(vwType);
			}
			return _id;
		},

		/*
		 *
		 */
		getVW : function(vwType) {
			var ed = this;
			//wenn nicht init
			if (!ed.data[vwType]) {
				ed.data[vwType] = ed.getDefaultVW(vwType);
			}
			return ed.data[vwType];
		},

		//for vw_docTyp
		getVW_by_form : function(vwType, $container) {
			var ed = this;
			var _checkValue = function($input) {
				$input.removeClass('fud-red-border');
				var _val = $.trim($input.val());
				var reg = $input.attr('data-reg');
				var _ok = true;
				if (_val == '') {
					if (reg != undefined) {
						_ok = false;
					}
				} else if (_ok && reg) {
					switch(reg) {
					case 'd':
						if (!_val.match(/^[0-9]+$/)) {
							_ok = false;
						};
						break;

					case 'w':
						break;
					}
				}

				if (!_ok) {
					//Show Error Dialog
					$('<div title="Fehler" class="fud-dialog-default"><p>Ungültige Eingaben!</p></div>').dialog();
					$input.addClass('fud-red-border');
					return false;
				}

				return [_val];
			};
			var obj = ed.getDefaultVW(vwType);
			var fList = $container.find(':input[name*="' + vwType + '_"]');
			for (var i = 0,
			    n,
			    v,
			    $f,
			    l = fList.length; i < l; i++) {
				$f = $(fList[i]);
				v = _checkValue($f);
				if (!v) {
					return null;
				} else {
					v = v[0];
				}
				n = $f.attr('name');
				n = n.replace(/[^_]*_[^_]*_/, '');
				obj[n] = v;
			}
			return obj;
		},

		/*
		 *
		 */
		itemAnimate : function($item) {
			$item.fadeOut(500).fadeIn(2000);
		},

		/*
		 *
		 */
		initialize : function(id) {
			this.editorID = id;
			this.historyData = Array();
			this.hasDoc = false;
			this.initGUI($(id));
		},

		/**
		 *
		 */
		initGUI : function($parent) {

			var ed = this;
			ed.actionResetDocType();
			ed.ui = {};
			$parent.mouseenter(function() {
				activeEditor = ed;
			});

			$parent.click(function() {
				activeEditor = ed;
			});

			ed.ui.editorButtons = Array();
			ed.ui.$dialogConfirm = $('<div title="Entfernen">Sind Sie sicher?</div>');
			ed.ui.blankFieldTemplate = '<li class="fud-tab-blank-li"><span>Leeres Feld</span></li>';
			ed.ui.$parent = $parent;

			ed.clipboard = ed.tabClipboard = ed.clipboardType = null;

			var $edc = ed.ui.$container = $($('#_test_').clone(true).html());
			//debug
			//product:		var edcText = '';
			//product:		var $edc = ed.ui.$container = $(edcText);
			$parent.append($edc);

			//toolbar
			var $toolbar = $edc.find('.fud-toolbar:first');

			//test button of toolbar
			$toolbar.find('a[name="fud_menuitem_demo"]:first').click(function(event) {
				ed.actionTest();
			});

			//new doctype (import from sql or create)
			var $dialogNewDoctype = ed.ui.$dialogNewDoctype = ed.bindButtonAndDialog($toolbar, 'fud_menuitem_new', 'fud-dialog-create-doctype', false);
			$dialogNewDoctype.dialog({
				open : function(event, ui) {
					$this = $(this);
					$this.find(':input[name*="vw_"]').val("");
				},
				buttons : {
					"Erstellen" : function() {
						if (ed.actionCreateNewDocType($dialogNewDoctype.find('.fud-create-doctype-container:first'))) {
							$dialogNewDoctype.dialog('close');
						}
					},
					"Abbrechen" : function() {
						$(this).dialog("close");
					}
				}
			});
			$dialogNewDoctype.find('input[name="submitCreate"]:first').click(function() {
				if (ed.actionCreateNewDocType($dialogNewDoctype.find('.fud-create-doctype-container:first'))) {
					$dialogNewDoctype.dialog('close');
				}
			});

			//new doctype import
			var $dialogImportDoctype = ed.ui.$dialogImportDoctype = ed.bindButtonAndDialog($toolbar, 'fud_menuitem_import', 'fud-dialog-import-doctype', false);
			var $importTextarea = ed.ui.$importTextarea = $dialogImportDoctype.find('textarea[name="fud_import_sql"]:first');
			$dialogImportDoctype.dialog({
				open : function(event, ui) {
					$importTextarea.val('');
					$importTextarea.focus();
				},
				buttons : {
					"Importieren" : function() {
						if (ed.actionSetSQL($importTextarea.val(), true)) {
							$dialogImportDoctype.dialog('close');
						}
					},
					"Abbrechen" : function() {
						$(this).dialog("close");
					}
				}
			});

			//setup doctype
			var $dialogSetupDoc = ed.bindButtonAndDialog($toolbar, 'fud_menuitem_setup_doctyp', 'fud-dialg-setup-doc', true);
			$dialogSetupDoc.dialog({
				open : function(event, ui) {
					ed.fillHtmlForm($(this), VW_METADATA, ed.getVW(VW_METADATA));
					ed.fillHtmlForm($(this), VW_DOCTYP, ed.getVW(VW_DOCTYP));
				},
				buttons : {
					"Bestätigen" : function() {
						var obj1 = ed.getVW_by_form(VW_DOCTYP, $dialogSetupDoc);
						var obj2 = ed.getVW_by_form(VW_METADATA, $dialogSetupDoc);
						if (obj1 && obj2) {
							var add2H = false;
							if (!ed.compareObj(obj1, ed.getVW(VW_DOCTYP))) {
								ed.setVW(VW_DOCTYP, _.toArray(obj1));
								add2H = true;
							}
							if (!ed.compareObj(obj2, ed.getVW(VW_METADATA))) {
								ed.setVW(VW_METADATA, _.toArray(obj2));
								add2H = true;
							}
							if (add2H) {
								ed.add2History();
							}

							$dialogSetupDoc.dialog("close");
						}

					},
					"Abbrechen" : function() {
						$(this).dialog("close");
					}
				}
			});

			//setup openDlg
			var $dialogCheckOpenDlg = $('<div title="Warnung">Es gibt Spalte, die nicht ausgef&uuml;llt ist, trotzdem weiter?</div>');
			$dialogCheckOpenDlg.dialog({
				autoOpen : false,
				modal : true,
				height : "auto",
				width : "auto",
				resizable : false,
				dialogClass : 'fud-dialog-default',
			});
			var $dialogSetupOpenDlg = ed.bindButtonAndDialog($toolbar, 'fud_menuitem_setup_openDlg', 'fud-dialg-setup-openDlg', true);
			//var $trDlgTitle = $dialogSetupOpenDlg.find('.dlg_tbl_title:first');//Tabelle horizontal darstellen:
			//var $trDlgContent = $dialogSetupOpenDlg.find('.dlg_tbl_content:first');
			var $tableDlg = $dialogSetupOpenDlg.find('.dlg_tbl:first');
			for (var i = 1; i < 14; i++) {
				$tableDlg.append('<tr><td style="text-align:center;width:5em">Spalte ' + i + '</td><td style="vertical-align:top"><input type="text" disabled="disabled" style="width:100%" name="' + VW_OPENDLG + '_spalte' + i + '"  /></td><td style="width:20px"><input title="bearbeiten" type="image" src="css/images/page_white_edit.png" /></td></tr>');
				//Tabelle horizontal darstellen:
				//	$trDlgTitle.append('<td>Spalte ' + i + ' </td>');
				//	$trDlgContent.append('<td style="vertical-align:top"><input title="bearbeiten" type="image" src="css/images/page_white_edit.png" /><input type="text" disabled="disabled" name="' + VW_OPENDLG + '_spalte' + i + '"  /></td>');
			}
			$dialogSetupOpenDlg.dialog({
				open : function() {
					if (!$dialogSetupOpenDlg.fudObjs) {
						var obj1 = _.clone(ed.getVW(VW_OPENDLG));
						//elementText statt id
						var idNameMap = {};
						_.each(ed.get_all_obj(), function(tabObj) {
							_.each(tabObj.liObj, function(feldObj) {
								idNameMap[feldObj.ID] = feldObj.elementText;
							});
						});
						var val,
						    nameArr;
						var obj2 = _.clone(obj1);
						for (p in obj1) {
							val = obj1[p];
							if (!val) {
								continue;
							}
							nameArr = _.map(val.split('#'), function(_id) {
								var ns = idNameMap[_id];
								if (ns) {
									return ns;
								}
							});
							obj2[p] = nameArr.join('#');
						}
						$dialogSetupOpenDlg.fudObjs = {
							"idObj" : obj1,
							"nameObj" : obj2
						};
					}
					ed.fillHtmlForm($(this), VW_OPENDLG, $dialogSetupOpenDlg.fudObjs.nameObj);
				},
				close : function() {
					if (!$dialogSetupOpenDlg.fudBlocked) {
						delete $dialogSetupOpenDlg.fudObjs;
						$dialogSetupOpenDlg.fudBlocked = false;
					}
				},
				buttons : {
					"Bestätigen" : function() {
						var that = this;
						var obj = $dialogSetupOpenDlg.fudObjs.idObj;
						var notFill = false;
						for (p in obj) {
							if (obj[p] == '') {
								notFill = true;
								break;
							}
						}
						if (notFill) {
							$dialogCheckOpenDlg.dialog({
								buttons : {
									"Weiter" : function() {
										if (!ed.compareObj(obj, ed.getVW(VW_OPENDLG))) {
											ed.data[VW_OPENDLG] = obj;
											ed.add2History();
										}
										$(that).dialog("close");
										$(this).dialog('close');
									},
									"Abbrechen" : function() {
										$(this).dialog("close");
									}
								}
							}).dialog('open');
						} else {
							//var obj = ed.getVW_by_form(VW_OPENDLG, $(this));
							//obj vergleichen
							if (!ed.compareObj(obj, ed.getVW(VW_OPENDLG))) {
								ed.data[VW_OPENDLG] = obj;
								ed.add2History();
							}

							$(that).dialog("close");
						}
					},
					"Abbrechen" : function() {
						$(this).dialog("close");
					}
				}
			});
			//dlg edit dialog
			var $dialogDlgEdit = ed.ui.$dialogDlgEdit = ed.bindButtonAndDialog(null, null, 'fud-dialog-dlg-edit', false);
			$tableDlg.find('input[type="image"]').click(function() {
				$dialogSetupOpenDlg.fudBlocked = true;
				//$dialogSetupOpenDlg.dialog("close");
				var $in = $(this).parent().parent().find('input[name*="' + VW_OPENDLG + '"]');
				var colID = $in.attr('name').replace(/[^_]*_[^_]*_/, '');
				var obj = {
					spalte_title : colID,
					spalte_data : $dialogSetupOpenDlg.fudObjs.idObj[colID]
				};
				ed.fillHtmlForm($dialogDlgEdit, VW_OPENDLG, obj);
				$dialogDlgEdit.fudObj = obj;
				$dialogDlgEdit.dialog('open');
				return false;
			});

			var $dialogDlgEditContainer = $dialogDlgEdit.find('*[name="dlg_spalte_edit_container"]:first');
			$dialogDlgEdit.dialog({
				open : function() {
					//var $in = $(this).find('input[name="vw_openDlg_spalte_data"]:first');
					var obj = $dialogDlgEdit.fudObj;
					//var objStr = $in.val();
					//ed.fill_dlg_edit($dialogDlgEditContainer, objStr);
					ed.fill_dlg_edit($dialogDlgEditContainer, obj.spalte_data);
				},
				close : function() {
					$dialogSetupOpenDlg.fudBlocked = false;
				},
				buttons : {
					"Bestätigen" : function() {
						var idArr = Array(),
						    nameArr = Array(),
						    _id,
						    _name;
						_.each($(this).find('select'), function(sel) {
							_id = $(sel).val();
							if (_id && _id != '') {
								idArr.push(_id);
								nameArr.push($(sel).find('option:selected').text());
							}
						});
						var obj = $dialogSetupOpenDlg.fudObjs;
						var colID = $dialogDlgEdit.fudObj.spalte_title;
						obj.idObj[colID] = idArr.join('#');
						obj.nameObj[colID] = nameArr.join('#');
						$dialogSetupOpenDlg.dialog("close");
						$dialogSetupOpenDlg.dialog("open");
						$(this).dialog("close");
						/*
						 var selectList = $t.find('select');
						 var st = $t.find('[name="vw_openDlg_spalte_title"]:first').val();
						 for (var i = 0, v, l = selectList.length; i < l; i++) {
						 v = $(selectList[i]).val();
						 if (v && v != '') {
						 idArr.push(v);
						 }
						 }
						 elementTextStr = spaltelementTextStreStr.replace(/^#/, '');
						 var $input = $dialogSetupOpenDlg.find('input[name="vw_openDlg_' + st + '"]:first');
						 $dialogSetupOpenDlg.dialog("open");
						 $input.val(elementTextStr);
						 $(this).dialog("close");*/
					},
					"Abbrechen" : function() {
						$dialogSetupOpenDlg.dialog("open");
						$(this).dialog("close");
					}
				}
			});

			$dialogDlgEdit.find('[name="dlg_add_item"]:first').click(function() {
				var $li = $dialogDlgEditContainer.find('li:first');
				var $li_clone = $li.clone(true);
				$li_clone.find('select').data('lastVal', '');
				$li_clone.insertBefore($li);
			});
			$dialogDlgEdit.find('[name="dlg_del_item"]:first').click(function() {
				$dialogDlgEditContainer.find('input:checked').each(function() {
					var $li = $(this).parent();
					if ($li.parent().children().length == 1) {
						$li.find('input:checked').prop('checked', false);
						$li_clone = $li.clone(true);
						$li_clone.insertAfter($li);
					}
					$li.remove();
				});
			});

			//export save as
			var $dialogExportSaveAs = ed.ui.$dialogExportSaveAs = ed.bindButtonAndDialog($toolbar, 'fud_menuitem_save_as', 'fud-dialog-export-save-as', true);
			//$dialogExportSaveAs.dialog();

			//export show sql text
			var $dialogExport = ed.ui.$dialogExport = ed.bindButtonAndDialog($toolbar, 'fud_menuitem_show_sql', 'fud-dialog-export-show-sql', true);
			$dialogExport.dialog({
				open : function(event, ui) {
					var result = ed.getSQL();
					$(this).find('textarea[name="fud_export_sql"]:first').val(result);
					$(this).find('div[name="fud_export_sql"]:first').html(ed.sql2TableHtml(result));
				},

				buttons : {
					"Ansicht: Tabelle/Text" : function() {
						$(this).find('div[name="fud_export_sql"]:first').toggle();
						$(this).find('textarea[name="fud_export_sql"]:first').toggle();
					},

					"Inhalt kopieren (todo)" : function() {
						//TODO
						$(this).dialog("close");
					},
					"Close" : function() {
						$(this).dialog("close");
					}
				}
			});

			var $dialogAbout = ed.ui.$dialogAbout = ed.bindButtonAndDialog($toolbar, 'fud_menuitem_about', 'fud-dialog-about', false);

			//Dialog: create new tab
			var $buttonCreateTab = ed.ui.$buttonCreateTab = $edc.find('input[name="create_tab_button"]:first');
			ed.ui.editorButtons.push($buttonCreateTab);
			$buttonCreateTab.click(function() {
				$dialogEditTab.$a = null;
				$dialogEditTab.dialog('open');
			});

			//Tab edit
			var $dialogEditTab = ed.ui.$dialogEditTab = ed.bindButtonAndDialog(null, null, 'fud-dialog-tab-edit');
			var $selectTabEdit = $dialogEditTab['select'] = $dialogEditTab.find('select[name="tab_name"]:first');
			$dialogEditTab['input'] = $dialogEditTab.find('input[name="tab_bezeichung"]:first');
			$dialogEditTab['eb'] = $dialogEditTab.find('input[name="tab_eb"]:first');
			for (var i = 0,
			    ft,
			    l = TAB_TYPEN.length; i < l; i++) {
				ft = TAB_TYPEN[i];
				$selectTabEdit.append('<option value="' + ft + '">' + ft + '</option>');
			}
			$dialogEditTab.dialog({
				buttons : {
					"Bestätigen" : function() {
						var $a = $dialogEditTab.$a,
						    $li;
						//new tab
						if (!$a) {
							var _obj = ed.getVW(VW_MASKTYP);
							_obj['Name'] = $dialogEditTab['select'].val();
							_obj['Bezeichnung'] = $dialogEditTab['input'].val();
							$li = ed.addNewTab(null, null, null, _obj, true)[0];
						} else {//edit
							$dialogEditTab.$a.html($dialogEditTab['input'].val());
							$dialogEditTab.$a.attr('data-fud_tab_name', $dialogEditTab['select'].val());
							$li = $a.parent();
						}
						ed.set_tab_eb($li, $dialogEditTab['eb'].is(':checked'));
						ed.add2History();
						$(this).dialog("close");
					},
					Cancel : function() {
						$(this).dialog("close");
					}
				},
				open : function() {
					var $a = $dialogEditTab.$a;
					if ($a) {
						$dialogEditTab['input'].val($a.html());
						$dialogEditTab['select'].val($a.attr('data-fud_tab_name'));
						if (ed.is_tab_eb($a.parent())) {
							$dialogEditTab['eb'].prop('checked', true);
						} else {
							$dialogEditTab['eb'].prop('checked', false);
						}
					} else {
						$dialogEditTab['input'].val('');
						$dialogEditTab['select'].val('inventarisierung');
						$dialogEditTab['eb'].prop('checked', false);
					}
					$dialogEditTab['input'].focus();
				}
			});

			//tabs (set tabs sortable)
			var $tabs = $edc.find('.fud-tabs:first');
			ed.ui.$tabs = $tabs;

			//<select></selcet>element for fieldtype
			var $feldTypenSelect = $edc.find('.fud-edit-field-select:first');
			for (var my_op in FELD_TYPEN) {
				$feldTypenSelect.append('<option value="' + my_op + '">' + FELD_TYPEN[my_op]['fieldTyp'] + '-' + FELD_TYPEN[my_op]['title'] + '</option>');
			}

			//undo
			var $undo = ed.ui.$undo = $toolbar.find('input[name="undo"]:first');
			$undo.click(function() {
				ed.actionUndo();
			});
			var $redo = ed.ui.$redo = $toolbar.find('input[name="redo"]:first');
			$redo.click(function() {
				ed.actionRedo();
			});

			//set tab sortable
			var $tabsNav = ed.ui.$tabsNav = $tabs.fudtabs().find(".ui-tabs-nav");
			$tabs.removeClass("ui-corner-all");
			$tabsNav.removeClass("ui-corner-all");
			$tabsNav.sortable({
				stop : function() {
					//	$tabs.fudtabs("refresh");
				},
				receive : function(event, ui) {
					var attr_role = ui.item.attr("role");
					if (!attr_role || attr_role != 'tab') {
						ui.sender.sortable("cancel");
					}
				},
				update : function() {
					ed.redoSortable = $(this);
					ed.add2History();
				}
			});

			// make all list of tab sortable
			$edc.find('.fud-tab-panel').sortable({
				axis : 'y',
				cursor : 'move',
				update : function() {
					ed.redoSortable = $(this);
					ed.add2History();
				}
			});

			//Dialog: create-new / edit field
			var $dialogEditField = ed.ui.$dialogEditField = $edc.find('.fud-edit-field:first').dialog({
				autoOpen : false,
				modal : true,
				width : "auto",
				dialogClass : 'fud-dialog-default',
				buttons : {
					"Bestätigen" : function() {
						var _data = $dialogEditField.fudFieldEditData;
						var $liItem,
						    editType,
						    obj,
						    recalc;

						for (p in _data) {
							editType = p;
							//edit / new
							$liItem = _data[p];
							break;
						}

						//Obj aus attribute "data" von html-element <li>...</li> erzeugen
						obj = ed.get_obj_of_li($liItem);
						if (editType == 'new' || editType == 'replace' || obj == null) {
							obj = ed.getDefaultVW(VW_MASK);
							recalc = true;
						}

						//Werte aus Formular lesen und Obj-Werte überschreiben
						var fList = $(this).find(':input[name*="vw_"]');
						var fl = fList.length;
						var $f,
						    k;
						while (fl--) {
							$f = $(fList[fl]);
							k = $f.attr('name');
							k = k.replace(/[^_]*_[^_]*_/, '');
							if (k == 'obligatory') {
								if ($f.is(':checked')) {
									obj[k] = '1';
								} else {
									obj[k] = '0';
								}
							} else {
								obj[k] = $f.val();
							}
						}
						//Neue ID generien
						if (recalc) {
							ed.recalc_vw_freeID(VW_MASK, obj['ID']);
						}

						//set 'tableTyp'
						var my_fty = obj['fieldTyp'];
						obj['tableTyp'] = FELD_TYPEN[my_fty]['tableTyp'];

						switch(my_fty) {
						case 'f-timelastchg':
							obj['fieldTyp'] = 'f';
							obj['tableName'] = 'domain';
							obj['tableField'] = 'timelastchg';
							break;

						case 'f-timecreate':
							obj['fieldTyp'] = 'f';
							obj['tableName'] = 'domain';
							obj['tableField'] = 'timecreate';
							break;

						case'k':
							obj['tableName'] = 'doc_anhang';
							break;

						case 'm':
							obj['tableName'] = 'doc_pic';
							break;

						case '9':
							obj['tableName'] = 'doc_volltext';
							break;
						}

						var newDivContent = SQLParser.vw_mask_data_2Html(obj);
						switch(editType) {
						case 'new':
							var $item = $('<li>' + newDivContent + '</li>');
							$item.insertAfter($liItem);
							ed.itemAnimate($item);
							break;

						case 'replace':
							var $item = $('<li>' + newDivContent + '</li>');
							$item.insertAfter($liItem);
							$liItem.remove();
							ed.itemAnimate($item);
							break;

						case 'edit':
							$liItem.empty();
							$liItem.append(newDivContent);
							ed.itemAnimate($liItem);
							break;
						}
						ed.formatTabPanel($liItem.parent());
						ed.add2History();
						$(this).dialog("close");
					},

					Cancel : function() {
						$(this).dialog("close");
					}
				},

				open : function(event, ui) {
					//<li><div>...</div></li>
					//div element. child of sortable li
					var _data = $dialogEditField.fudFieldEditData;
					var $liItem = _data['edit'];
					var obj;
					if ($liItem) {//edit, otherwise add new
						obj = ed.get_obj_of_li($liItem);
					}

					if (!obj) {
						obj = ed.getDefaultVW(VW_MASK);
						obj['ID'] = ed.get_vw_freeID(VW_MASK, false);
					}

					var _tableField = obj['tableField'];
					if (_tableField == 'timecreate') {
						//my_fieldTyp
						obj['fieldTyp'] = 'f-timecreate';

					} else if (_tableField == 'timelastchg') {
						//my_fieldTyp
						obj['fieldTyp'] = 'f-timelastchg';
					}

					ed.fillHtmlForm($(this), VW_MASK, obj);
				}
			});

			ed.setActionButtons(false);

			//set ContextMemu;
			ed.setContexMenu();

			//layout
			var _layout = function() {
				var edcH = $edc.height();
				var edcW = $edc.width();
				$tabs.height($edc.height() - $toolbar.height() - 20);
				$dialogExport.find('.fud_export_container').css({
					height : (edcH * 0.8),
					width : (edcW * 0.8),
				});

				$dialogSetupOpenDlg.find('.dlg_tbl_container').css({
					width : (edcW * 0.7),
				});
			};

			//Bei ersten Laden durchfuehren
			_layout();

			$(window).resize(function() {
				_layout();
			});
		},

		/*
		 *
		 */
		insertFieldToTab : function($tab, liContent) {
			var _id = $tab.find('a:first').attr('href');
			var $ul = $(_id).find('ul:first');
			var $liField = $('<li>' + liContent + '</li>');
			$ul.append($liField);
		},

		/*
		 *
		 */
		isObjEmpty : function(obj, arr) {
			for (var p in obj) {
				if ($.inArray(p, arr) !== -1) {
					continue;
				}
				if (obj[p] != '') {
					return true;
				}
			}
			return false;
		},

		/*
		 *
		 */
		is_tab_eb : function($li) {
			var $span = $li.find('.fud-tab-eb:first');
			var iseb = $span.attr('data-iseb');
			if (iseb == undefined || iseb == '') {
				return false;
			}
			return true;
		},

		/*
		 *
		 */
		push_sql_2_vw_mask_array : function(arr, vwType, liList, vw_maskTypID, sortArr) {
			var ed = this;
			var _getSn = function(_sn) {
				if (_sn < 9) {
					return ++_sn;
				} else if (_sn == 9) {
					return 'a';
				} else {
					var az = "abcdefghijklmnopqrstuvwxyz";
					return az.charAt(az.indexOf(_sn) + 1);
				}
			};

			var previousIsAnhang = false;
			for (var i = 0,
			    $li,
			    sn = -1,
			    l = liList.length; i < l; i++) {
				$li = $(liList[i]);
				if ($li.hasClass("fud-tab-blank-li")) {
					continue;
				}
				var $liDiv = $li.find('.fud-field-container:first');
				var attrData = $liDiv.attr('data-fudfield');
				//change propertiy 'maskTypID <=> vw_maskID'
				if (vwType == VW_MASK) {
					attrData = attrData.replace(/&vw_maskID=/, '&maskTypID=');
				} else if (vwType == VW_MASKSUB) {
					attrData = attrData.replace(/&maskTypID=/, '&vw_maskID=');
				}

				var obj = deparam(attrData);
				//set sourcename_idx and title_idx
				if (previousIsAnhang) {
					obj['tableField'] = 'anhang_title' + (sn);
					obj['tableName'] = 'extend';
					previousIsAnhang = false;
				}
				if (obj['fieldTyp'] == 'k') {
					sn = _getSn(sn);
					obj['tableField'] = 'sourcename' + sn;
					previousIsAnhang = true;
				}

				obj['sort'] = sortArr[vwType];
				sortArr[vwType] = sortArr[vwType] + 5;
				if (vwType == VW_MASK) {
					obj['maskTypID'] = vw_maskTypID;
					if (obj['fieldTyp'] == 'k') {
						obj['tableName'] = 'doc_anhang';
					} else if (obj['fieldTyp'] == 'f' && (obj['tableField'] == 'timecreate' || obj['tableField'] == 'timelastchg')) {

					} else {
						obj['tableName'] = 'extend';
					}
					//Immer so ? TODO was ist mit dummy?
				} else if (vwType == VW_MASKSUB) {
					obj['vw_maskID'] = vw_maskTypID;
					obj['tableName'] = 'extend_sub';
					//Immer so ? TODO
				}

				ed.vw_mask_data_set_extra(obj);
				ed.obj2sql(arr, obj);
			}
			return arr;
		},

		/*
		 *
		 */
		obj2sql : function(arr, obj) {
			var ed = this;
			var str = '';
			var v;
			for (var p in obj) {//test
				//	if (p != 'tableField' && p != 'tableName')
				//	continue;
				if (p.match(/^tmp_/)) {
					continue;
				}

				v = obj[p];
				if (!v || v == '') {
					v = "''";
				} else if (isNaN(v)) {
					v = v.replace(/'/g, '\\\'');
					v = "'" + v + "'";
				}
				str += v + ",";
			}
			str = str.replace(/,$/, '');
			str = "(" + str + ")";
			if (arr) {
				arr.push(str);
			}
			return str;
		},

		/*
		 * only for vw_mask::ID, vw_masksub and vw_maskType::ID
		 */
		recalc_vw_freeID : function(vwType, currID) {
			var ed = this;
			if (vwType == VW_MASKSUB) {
				vwType = VW_MASK;
			}
			var obj = ed.getVW(vwType);
			var freeID = ed.data.freeID[vwType];
			currID = parseInt(currID);
			if (!freeID || (currID >= freeID)) {
				ed.data.freeID[vwType] = currID + 1;
			}
		},

		/*
		 *
		 */
		setActionButtons : function(b) {
			var ed = this;
			var buttons = ed.ui.editorButtons;
			for (var i = 0,
			    bt,
			    l = buttons.length; i < l; i++) {
				bt = buttons[i];
				if (b) {
					if ($(bt).is("a")) {
						bt.removeClass('fud-a-disabled');
					} else {
						bt.removeAttr('disabled');
					}
				} else {
					if ($(bt).is("a")) {
						bt.addClass('fud-a-disabled');
					} else {
						bt.attr('disabled', 'disabled');
					}
				}
			}
			ed.hasDoc = b;
		},

		/*
		 * If tab panel is empty, use this menu
		 */
		setContexMenu : function() {
			$.contextMenu({
				selector : '.fud-tab-blank-li',
				items : {
					"new" : {
						name : "Neues Felder",
						icon : "add",
						callback : function(_key, _options) {
							var ed = activeEditor;
							var $f_d = ed.ui.$dialogEditField;
							$f_d.fudFieldEditData = {
								'replace' : _options.$trigger
							};
							$f_d.dialog('open');
						}
					},
					"insert" : {
						name : "Einfügen",
						icon : "paste",
						callback : function(_key, _options) {
							var ed = activeEditor;
							var $item = ed.clipboard;
							if (!$item)
								return;

							if (ed.clipboardType == 'copy') {
								$item = $item.clone(true);
								ed.updateFieldItemValue($item);
							} else {
								ed.clipboard = null;
							}

							if (ed.clipboardType == 'cut') {
								ed.checkAndAddBlankField($item);
							}

							$item.insertAfter(_options.$trigger);
							ed.formatTabPanel($item.parent());
							_options.$trigger.remove();
							ed.itemAnimate($item);
						},
						disabled : function(key, opt) {
							var ed = activeEditor;
							if (ed.clipboard == null)
								return true;
							else
								return false;
						}
					},
				}
			});

			////////////////////////////////// contextMenu für Felder ///////////////////////////////////////
			$.contextMenu({
				selector : '.fud-tab-panel li:not(.fud-tab-blank-li)',
				callback : function(key, options) {
				},
				events : {
					show : function(opt) {
						this.addClass('fud-li-selected');
						this.trigger('click');
					},
					hide : function(opt) {
						this.removeClass('fud-li-selected');
					}
				},
				items : {
					"new" : {
						name : "Neues Felder",
						icon : "add",
						callback : function(_key, _options) {
							var ed = activeEditor;
							var $f_d = ed.ui.$dialogEditField;
							$f_d.fudFieldEditData = {
								'new' : _options.$trigger
							};
							$f_d.dialog('open');
						}
					},
					"sep0" : "---------",
					"edit" : {
						name : "Editieren",
						icon : "edit",
						callback : function(_key, _options) {
							var ed = activeEditor;
							var $f_d = ed.ui.$dialogEditField;
							$f_d.fudFieldEditData = {
								'edit' : _options.$trigger
							};
							$f_d.dialog('open');
						}
					},
					"cut" : {
						name : "Ausschneiden",
						icon : "cut",
						callback : function(_key, _options) {
							var ed = activeEditor;
							$item = _options.$trigger;
							ed.clipboard = $item;
							ed.clipboardType = 'cut';
							ed.itemAnimate($item);
						}
					},
					"copy" : {
						name : "Kopieren",
						icon : "copy",
						callback : function(_key, _options) {
							var ed = activeEditor;
							ed.clipboardType = 'copy';
							ed.clipboard = _options.$trigger.clone(true).attr('class', '');
						}
					},
					"insert-before" : {
						name : "Einfügen vor",
						icon : "paste",
						callback : function(_key, _options) {
							var ed = activeEditor;
							var $item = ed.clipboard;
							if (!$item)
								return;
							if (ed.clipboardType == 'copy') {
								$item = $item.clone(true);
								ed.updateFieldItemValue($item);
							} else {
								ed.clipboard = null;
							}

							if (ed.clipboardType == 'cut') {
								ed.checkAndAddBlankField($item);
							}

							$item.insertBefore(_options.$trigger);
							ed.formatTabPanel($item.parent());
							ed.itemAnimate($item);
							ed.add2History();
						},
						disabled : function(key, opt) {
							var ed = activeEditor;
							if (ed.clipboard == null)
								return true;
							else
								return false;
						}
					},
					"insert-after" : {
						name : "Einfügen nach",
						icon : "paste",
						callback : function(_key, _options) {
							var ed = activeEditor;
							var $item = ed.clipboard;
							if (!$item)
								return;

							if (ed.clipboardType == 'copy') {
								$item = $item.clone(true);
								ed.updateFieldItemValue($item);
							} else {
								ed.clipboard = null;
							}

							if (ed.clipboardType == 'cut') {
								ed.checkAndAddBlankField($item);
							}

							$item.insertAfter(_options.$trigger);
							ed.formatTabPanel($item.parent());
							ed.itemAnimate($item);
							ed.add2History();
							;
						},
						disabled : function(key, opt) {
							var ed = activeEditor;
							if (ed.clipboard == null)
								return true;
							else
								return false;
						}
					},
					"sep1" : "---------",
					"delete" : {
						name : "Entfernen",
						icon : "delete",
						callback : function(_key, _options) {
							var ed = activeEditor;
							ed.ui.$dialogConfirm.dialog({
								resizable : false,
								height : "auto",
								width : "auto",
								dialogClass : 'fud-dialog-default',
								modal : true,
								open : function(event, ui) {
									var $it = _options.$trigger;
									$it.css('background-color', '#F39814');
								},
								buttons : {
									"Entfernen" : function() {
										var ed = activeEditor;
										var $it = _options.$trigger;
										ed.checkAndAddBlankField($it);
										ed.add2History();
										$it.remove();
										$(this).dialog("close");
									},
									"Abbrechen" : function() {
										$(this).dialog("close");
									}
								},
								close : function() {
									_options.$trigger.css('background-color', '#D5DDE0');
								}
							});
						}
					}
				}
			});

			///////////////////////////////////// contextMenu für Tabs //////////////////////////////////////
			$.contextMenu({
				selector : '.fud-tabs li',
				events : {
					show : function(opt) {
						var $this = this;
						$this.trigger('click');
						$this.focus();
					}
				},
				items : {
					"edit" : {
						name : "Editieren",
						icon : 'edit',
						callback : function(_key, _options) {
							var ed = activeEditor;
							var $dialog = ed.ui.$dialogEditTab;
							$dialog.$a = _options.$trigger.find('a');
							$dialog.dialog('open');
						},
						disabled : function(key, opt) {
							return opt.$trigger.find('input[name="create_tab_button"]').length > 0;
						}
					},

					"copyseparator" : "---------",
					"copy" : {
						name : "Tab kopieren",
						icon : "copy",
						callback : function(_key, _options) {
							var ed = activeEditor;
							ed.clipboardType = 'copy';
							ed.tabClipboard = _options.$trigger.clone(true).attr('class', '');
						},
						disabled : function(key, opt) {
							return opt.$trigger.find('input[name="create_tab_button"]').length > 0;
						}
					},
					"insert-before" : {//nur für kopieren, keine Ausschneiden
						name : "Einfügen vor",
						icon : "paste",
						callback : function(_key, _options) {
							var ed = activeEditor;
							var $item = ed.tabClipboard;
							if (!$item || $item.length < 1) {
								return;
							}

							$item = ed.addNewTab($item, _options.$trigger, null)[0];
							ed.add2History();
							$item.fadeOut(500).fadeIn(2000);
						},

						disabled : function(key, opt) {
							var ed = activeEditor;
							if (ed.tabClipboard == null)
								return true;
							else
								return false;
						}
					},
					"insert-after" : {//nur für kopieren, keine Ausschneiden
						name : "Einfügen nach",
						icon : "paste",
						callback : function(_key, _options) {
							var ed = activeEditor;
							var $item = ed.tabClipboard;
							if (!$item || $item.length < 1)
								return;

							$item = ed.addNewTab($item, null, _options.$trigger)[0];
							ed.add2History();
							$item.fadeOut(500).fadeIn(2000);
						},
						disabled : function(key, opt) {
							var ed = activeEditor;
							if (ed.tabClipboard == null)
								return true;
							else
								return opt.$trigger.find('input[name="create_tab_button"]').length > 0;
						}
					},
					"deleteseparator" : "---------",
					"delete" : {
						name : "Entfernen",
						icon : "delete",
						callback : function(_key, _options) {
							var ed = activeEditor;
							ed.ui.$dialogConfirm.dialog({
								resizable : false,
								height : "auto",
								width : "auto",
								dialogClass : 'fud-dialog-default',
								modal : true,
								buttons : {
									"Entfernen" : function() {
										var ed = activeEditor;
										ed.add2History();
										ed.ui.$tabs.fudtabs('removeTab', _options.$trigger);
										$(this).dialog("close");
									},
									"Abbrechen" : function() {
										$(this).dialog("close");
									}
								}
							});
						},
						disabled : function(key, opt) {
							return opt.$trigger.find('input[name="create_tab_button"]').length > 0;
						}
					}
				}
			});
		},

		/*
		 *
		 */
		set_tab_eb : function($tabLi, b) {
			var $eb = $tabLi.find('.fud-tab-eb:first');
			if (b) {
				$eb.attr('data-iseb', '1');
				$eb.html("*");
			} else {
				$eb.removeAttr('data-iseb');
				$eb.html("");
			}
		},

		/*
		 *
		 */
		setVW : function(vwType, valArr) {
			var ed = this;
			var obj = ed.getVW(vwType);
			var i = 0;
			for (var p in obj) {
				if (i >= valArr.length) {
					break;
				}
				if (p == 'ID' && (vwType == VW_MASK || vwType == VW_MASKTYP || vwType == VW_MASKSUB)) {
					ed.recalc_vw_freeID(vwType, valArr[i]);
				}

				obj[p] = valArr[i];
				i++;
			}
			return obj;
		},

		/*
		 *
		 */
		sql2TableHtml : function(sqlStr) {
			var arr = sqlStr.split('\n');
			var out = '';
			for (var i = 0,
			    s,
			    isInsert,
			    l = arr.length,
			    line; i < l; i++) {
				line = arr[i];
				if (line.match(/^INSERT\s+INTO/)) {
					isInsert = true;
					out += '<table class="sql_export_table"><tr><td>';
					line = line.replace(/\(`/, '</td><td style="font-weight:bold; text-align:center; color:#000000;">');
					line = line.replace(/`,`/g, '</td><td style="font-weight:bold; text-align:center; color:#000000">');
					line = line.replace(/\)\s+VALUES/, '</td></tr>');
					line = line.replace(/`/g, '');
					out += line;
					s = true;

				} else if (s == true && line.match(/^\(.*\)/)) {
					var reg = /\(.*\)/ig;
					var regArr = line.match(reg);

					if (!regArr) {
						continue;
					}
					line = regArr[0];
					line = line.substring(1, line.length - 1);
					var lineArr = SQLParser.rowToArray(line);
					var valStr = '';
					if (isInsert == false) {
						valStr = '<tr><td></td>';
					} else {
						valStr = '<tr><td>VALUES</td>';
					}

					for (var x = 0,
					    tdStr,
					    y = lineArr.length; x < y; x++) {
						tdStr = lineArr[x];
						tdStr = $("<div/>").text(tdStr).html();
						valStr += '<td style="color:blue">' + tdStr + '</td>';
					}
					valStr += '</tr>';
					out += valStr;
					isInsert = false;
				} else {
					if (s == true) {
						out += '</table>';
						s = false;
					} else {
						out += line + '<br />';
					}
					isInsert = false;
				}
			}
			return out;
		},

		/*
		 * <li> item
		 */
		updateFieldItemValue : function($item) {
			var ed = this;
			var $div = $item.find('.fud-field-container:first');
			if ($div) {
				var attrData = $div.attr('data-fudfield');
				var obj = ed.get_obj_of_li($item);
				var nID = ed.get_vw_freeID(VW_MASK, true);
				var nTableField = obj['tableField'].split('__')[0];
				nTableField = ed.getStringMax(nTableField, 250) + "__" + nID;
				obj['tableField'] = nTableField;
				obj['ID'] = nID;
				$div.attr('data-fudfield', param(obj));
			}
		},

		/*
		 *
		 */
		use_vw_freeID : function(vwType) {
			var ed = this;
			if (vwType == VW_MASKSUB) {
				vwType = VW_MASK;
			}
			ed.data.freeID[vwType] = ed.data.freeID[vwType] + 1;
		},

		/*
		 *
		 */
		vw_mask_data_set_extra : function(obj) {
			var ed = this;
			//set tableName  ,tableField
			$updateTableField = false;
			if (obj['tableName'] == '@') {
				if (obj['fieldTyp'] == 'b') {
					obj['tableName'] == 'dumy';
				} else {
					obj['tableName'] = 'extend';
				}
				$updateTableField = true;
				//obj['tableField'] = ed.getStringMax(obj['ID'] + '_' + obj['sort'] + '_' + obj['elementText'].toLowerCase(), 250);
			}

			if ($updateTableField == true || obj['tableField'] == '@') {
				obj['tableField'] = ed.getStringMax(obj['ID'] + '_' + obj['sort'] + '_' + obj['elementText'].toLowerCase(), 250);
			}

			//set 'indexTable'
			var fieldTyp = obj['fieldTyp'];
			if (obj['indexTable'] == '@') {
				if (fieldTyp == 'e' || fieldTyp == 'g' || fieldTyp == 'y') {
					obj['indexTable'] = 'idx_' + obj['tableField'];
				} else {
					obj['indexTable'] = '';
				}
			}
		},

		/*
		 *
		 */
		vw_dlg_data2obj : function(vwType) {
			var ed = this;
			var spalteStr;
			var obj = ed.getVW(vwType);
			var newObj = {};
			for (var p in obj) {
				if (!p.match(/spalte/)) {
					continue;
				}
				spalteStr = obj[p];
				if (spalteStr && spalteStr != '' && spalteStr != undefined) {
					newObj[p] = spalteStr.split('#');
				} else {
					newObj[p] = Array();
				}
			}
			return newObj;
		},
	};

	/********************************************************************/
	/**                         API				                       **/
	/********************************************************************/
	var API = {
		bind : function(id) {
			$(document).ready(function() {
				if (_.indexOf(editors, id) >= 0) {
					console.log("Editor exist!!!");
					return;
				};
				editors.push(id);
				new Editor(id);
			});

		}
	};
	return API;
});
